package com.zyy.java8.samples.misc;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;

/**
 * @author zhangyiying
 * @ClassName: Concurrency1
 * @Description:
 * @date 2022/3/16 19:55
 */
public class Concurrency1 {
    public static void main(String[] args) {
        ConcurrentHashMap<Integer, UUID> concurrentHashMap = new ConcurrentHashMap<>();
        init(concurrentHashMap);

//        test1(concurrentHashMap);
//        test2(concurrentHashMap);
        test3(concurrentHashMap);


    }

    /**
     * 初始化ConcurrentHashMap
     * @param concurrentHashMap
     */
    private static void init(ConcurrentHashMap concurrentHashMap){
        for (int i = 0; i < 100; i++) {
            concurrentHashMap.put(i, UUID.randomUUID());
        }
    }

    /**
     * 测试ConcurrentHashMap多线程处理并发时的效率
     */
    private static void test1(ConcurrentHashMap concurrentHashMap){

        int threshold1 = 1;
        int threshold2 = 5;
        Consumer<UUID> printConsumer = uuid -> {
            String threadName = Thread.currentThread().getName();
            System.out.println(String.format("%s : %s", threadName, uuid));
        };

        long start01 = System.currentTimeMillis();
        concurrentHashMap.forEachValue(threshold1, printConsumer);
        long end01 = System.currentTimeMillis();
        System.out.println();
        System.out.println("threshold1耗时：" + (end01 - start01));


        long start02 = System.currentTimeMillis();
        concurrentHashMap.forEachValue(threshold2, printConsumer);
        long end02 = System.currentTimeMillis();
        System.out.println();
        System.out.println("threshold2耗时：" + (end02 - start02));
    }

    private static void test2(ConcurrentHashMap<Integer, UUID> concurrentHashMap){
        concurrentHashMap.forEach((id, uuid) -> {
            if (id % 10 == 0) {
                System.out.println(String.format("%s: %s", id, uuid));
            }
        });
    }

    private static void test3(ConcurrentHashMap<Integer, UUID> concurrentHashMap){
        int threshold = 1;
        concurrentHashMap.forEach(threshold, (id, uuid) -> {
            System.out.println(String.format("%s: %s", id, uuid));
        });


        UUID searchResult = concurrentHashMap.search(threshold, (id, uuid) -> {
            if (String.valueOf(uuid).startsWith(String.valueOf(id))) {
                return uuid;
            }
            return null;
        });

        System.out.println(searchResult);
    }
}
